<template>
	<view>
		<view v-if="loading" class="data">
			<text class="item-title">{{blog.title}}</text>
			<text class="time">{{blog.user.userName+" @   "+blog.createTime}}</text>
			<rich-text class="item-desc" :nodes="blog.content"></rich-text>
			<image class="rich-img" :src="blog.picture" mode="widthFix"></image>
			<view>
				<text v-for="(tag,idx) in blog.tags" class="item-tag" :key="idx">{{tag}}</text>
			</view>
			<view class="icons-container">
				<text @click.stop="changeGood(blog.id)"
					:class="good_ids.indexOf(blog.id)>=0?'iconfont icon-pyro1 icon_good':'iconfont icon-pyro1 icon'"></text>
				<text class="icon-text">{{blog.good}}</text>
				<text class="iconfont icon-genshin_game_map_liyue icon" style="color:gray;"></text>
				<text class="icon-text">{{blog.comments.length}}</text>
				<text class="iconfont icon-genshin_game_map_xumi icon" style="color:goldenrod;"></text>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
			<image class="img-avatar" :src="blog.user.avatar" mode="aspectFill"></image>

			<text class="iconfont icon-genshin_game_sign_genshin label" @click.stop="drop(blog.id)"
				style="color:#747868;"></text>

		</view>
		<view class="blog-margin">
			<view v-if="parents.length>0" v-for="(item ,index) in parents" :key="index">
				<view class="cmt-container">
					<image :src="item.avatar" class="cmt-avatar"></image>
					<text class="cmt-nick">{{item.nickName }}</text>
					<view class="cmt-time-container">
						<text class="cmt-time">{{item.createTime }}</text>
						<text class="txt-del">[删除]</text>
					</view>
					<text class="cmt-text" @click="clickReply(item)">{{item.content }}</text>
					<view class="replies-container">
						<view v-for="(arr,idx) in replies[index]" :key="idx" class="reply">
							<view class="reply-info">
								<text class="reply-nick">{{arr.nickName}}</text>
								<text class="reply-to">@{{arr.toUser}}</text>
								<text class="reply-time">{{arr.createTime}}</text>
								<text class="txt-del">[删除]</text>

							</view>
							<text class="reply-content" @click="clickReply(item)">{{arr.content}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="input-container">
			<image :src="useravatar" mode="aspectFill" class="input-avatar" @click="clickLogin"></image>

			<textarea @input="inputGetValue" auto-height :placeholder="inputHolder" class="input"
				placeholder-class="input-holder"></textarea>
			<image src="../../static/icons/commit.png" mode="aspectFill" class="input-img" @click="clickCommit()">
			</image>
		</view>
		<login-dailog ref="login" @after="afterlogin">

		</login-dailog>
	</view>
</template>

<script>
	let parentId = null

	export default {
		data() {
			return {
				blog: {},
				parents: [],
				replies: [],
				good_ids: [],
				loading: false,
				inputHolder: "请输入评论内容",
				inputValue: "",
				useravatar: "/static/icons/default_user.png",
			}
		},
		onLoad(options) {
			this.$noti.register(this.$par.notice_login_status,this.afterLogin,this)
			let ids = uni.getStorageSync(this.$par.key_good_ids)
			if (ids != 0) {
				this.good_ids = ids
			}
			let id = options.id
			this.addReadCount(id)

		},
		onUnload(){
			this.$noti.remove(this.$par.notice_login_status,this)
		},
		methods: {
			afterlogin() {
				this.useravatar = this.$par.host + getApp().globalData.avatar
			},
			getBlog(id) {
				let url = this.$par.host + this.$par.action_top_blogs + id
				uni.showLoading({
					title: '加载中',
					mask: false
				});
				this.$req.get(url, res => {
					let item = res.data.data; // 直接赋值
					uni.setNavigationBarTitle({
						title: item.user.nickName
					})
					item.picture = this.$par.host + item.picture
					item.user.avatar = this.$par.host + item.user.avatar
					item.content = item.content.replace(/\<img/gi, '<img class="rich-img"')
					item.createTime = this.$util.formatTime(new Date(item.createTime))
					item.updateTime = this.$util.formatTime(new Date(item.updateTime))
					this.formatComments(item.comments)
					this.blog = item
					this.loading = true
					uni.hideLoading()
				}, () => {
					uni.hideLoading()
				})
			},
			formatComments(comments) {
				if (comments.lenght == 0) {
					return
				}
				let parents = []
				comments.forEach(c => {
					c.avatar = this.$par.host + c.avatar.substring(1)
					c.createTime = this.$util.formatTime(new Date(c.createTime))
					if (c.parentId == null) {
						parents.push(c)
					}
				})
				parents.sort((c1, c2) => {
					return new Date(c2.createTime).getTime() - new Date(c1.createTime).getTime()
				})
				let replies = new Array(parents.length).fill([])
				let index = 0
				parents.forEach(p => {
					let cmmts = []
					cmmts = [...cmmts, ...this.getAllChildren(p, comments)]
					replies[index++] = cmmts
				})
				this.parents = parents
				this.replies = replies
			},
			getAllChildren(parent, comments) {
				let result = []
				if (comments) {
					comments.forEach(c => {
						if (c.parentId == parent.id) {
							c.toUser = parent.nickName
							result.push(c)
							result = [...result, ...this.getAllChildren(c, comments)]
						}
					})
				}
				return result
			},
			addReadCount(id) {
				let url = this.$par.host + this.$par.action_read_count
				let data = {
					"id": id
				}
				this.$req.postQuery(url, data, res => {
					//console.log(res)
					let count = res.data.data
					this.$noti.post(this.$par.notice_refresh_count, {
						id,
						count,
					})
					// let pages=getCurrentPages()
					// let prev=pages[pages.length-2]
					// prev.refreshReadCount(id,count)

				}, () => {
					this.getBlog(id)
				})
			},

			changeGood(id) {
				let good = true
				if (this.good_ids.indexOf(id) >= 0) {
					good = false
				}
				if (good) {
					this.good_ids = [...this.good_ids, id]
				} else {
					//splice删除指定位置元素
					//shift删除第一个
					//pop删除最后一个
					let pos = this.good_ids.indexOf()
					this.good_ids.splice(pos, 1)
					// this.good_ids.shift()
					// this.good_ids.pop()
				}
				uni.setStorageSync(this.$par.key_good_ids, this.good_ids)
				this.postGood(id, good)
			},
			//发送数据到服务器，修改点赞数量+1或-1，服务器服务器返回最新的点赞数量
			postGood(id, good) {
				uni.showLoading({
					title: '点赞成功',
					mask: false
				});
				let url = this.$par.host
				let action = good ? this.$par.action_good : this.$par.action_del_good
				url += action
				let data = {
					"id": id
				}
				this.$req.postQuery(url, data, res => {
						// console.log(res)

						if (this.blog.id == id) {
							this.blog.good = res.data.data
						}

					},

					() => {
						uni.hideLoading()
					})
			},
			drop(id) {
				uni.showActionSheet({
					itemList: ["屏蔽该条博客", "举报该条博客"],
					success: res => {
						// console.log(res)
						if (res.tapIndex == 0) {
							//使用缓存保存要屏蔽的blod的id，然后在getPagedBlogs中读取缓存，匹配中的则不添加到this.blog
							uni.showModal({
								title: '确认',
								content: '确认屏蔽该条博客吗？',
								showCancel: true,
								cancelText: '取消',
								confirmText: '确定',
								success: res => {
									if (res.confirm) {
										uni.showToast({
												title: '已屏蔽，以后会给您减少相关内容的推荐',
												duration: 3000,
											}),
											uni.navigateBack({
												delta: 2
											});
									} else if (res.cancel) {
										uni.showToast({
											title: '已取消屏蔽',
											duration: 3000
										});
									}
								},
								fail: function(res) {
									console.log(res.errMsg)
								},
								complete: () => {}
							});
						} else if (res.tapIndex == 1) {
							uni.showModal({
								title: '确认',
								content: '确认举报该条博客吗？',
								showCancel: true,
								cancelText: '取消',
								confirmText: '确定',
								success: res => {
									if (res.confirm) {
										uni.showToast({
											title: '已举报，感谢您为网站净化做出的贡献',
											duration: 3000
										});
									} else if (res.cancel) {
										uni.showToast({
											title: '已取消举报',
											duration: 3000
										});
									}
								},
								fail: function(res) {
									console.log(res.errMsg)
								},
								complete: () => {}
							});
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			clickReply(reply) {
				console.log(reply)
				parentId = reply.id
				this.inputHolder = "@" + reply.nickName

			},
			clickCommit(e) {
				console.log(parentId, this.inputValue);
			},
			inputGetValue(e) {
				this.inputValue = e.detail.value
			},
			clickLogin() {
				this.$refs.login.show()
			}

		},

	}
</script>

<style>
	@import url("detail.css");
</style>